<template>
  <!--个人中心主页-->
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/myInfo' }">个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>我的资料</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <div class="myleft">
        <img :src="myself.img" />
      </div>
      <div class="myright">
        <el-row :gutter="20">
          <el-col :span="10">
            <span class="mytitle">名片:</span>
          </el-col>
          <el-col :span="10">编辑<i class="el-icon-edit" @click="showEditDialog()"></i></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            用户名：<span class="mytitle">{{myself.username}}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            电子邮件：<span class="mytitle">{{myself.email}}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            电话号码：<span class="mytitle">{{myself.phone}}</span>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="55%" @close="editDialogClosed">
      <el-form :model="myself" :rules="myselfRules" ref="myselfRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="myself.username" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="myself.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="myself.phone" disabled></el-input>
        </el-form-item>
        <el-form-item>
          <template>
            <span>原图</span>
            <el-avatar shape="square" :size="100" fit="cover" :src="myself.img"></el-avatar>
          </template>
          <el-upload :auto-upload="false" :on-change="onchange" :on-remove="handleRemove" :limit="1" list-type="picture-card"
            action="#">
            <i class="el-icon-plus"></i>
          </el-upload>
          <!--图片展示-->
          <el-dialog>
            <img width="100%" :src="src" alt="">
          </el-dialog>

        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    data() {
      // 验证邮箱的规则
      var checkEmail = (rule, value, cb) => {
        // 验证邮箱的正则表达式
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

        if (regEmail.test(value)) {
          // 合法的邮箱
          return cb()
        }

        cb(new Error('请输入合法的邮箱'))
      }
      // 验证手机号的规则
      var checkphone = (rule, value, cb) => {
        // 验证手机号的正则表达式
        const regphone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

        if (regphone.test(value)) {
          return cb()
        }

        cb(new Error('请输入合法的手机号'))
      }
      return {
        //上传图片
        src: '', //图片预览地址
        newsrc:'',//保存新的路径
        myself: {}, //当前用户信息
        // 控制修改用户对话框的显示与隐藏
        editDialogVisible: false,
        // 查询到的用户信息对象
        editForm: {},
        // 修改表单的验证规则对象
        myselfRules: {
          email: [{
              required: true,
              message: '请输入用户邮箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ],
          phone: [{
              required: true,
              message: '请输入用户手机',
              trigger: 'blur'
            },
            {
              validator: checkphone,
              trigger: 'blur'
            }
          ]
        }
      }
    },
    mounted() {
      //获取当前用户信息
      this.getUserList();
    },
    methods: {
      //根据id查询用户信息
     async getUserList(){
        var id=JSON.parse(window.sessionStorage.getItem("user")).userid;
        const {
          data: res
        } = await this.$axios.post(
          'UserController/findUserOne.action?id='+id
        )
        console.log(res);
        if (!res) return this.$message.error('获取信息失败！');
        //重新设置信息
        window.sessionStorage.setItem("user",JSON.stringify(res));
        this.myself=res;
      },
      // 展示编辑用户的对话框
      showEditDialog() {
        this.editDialogVisible = true
      },
      // 监听修改用户对话框的关闭事件
      editDialogClosed() {
        this.$refs.myselfRef.resetFields() // 重置表单
      },
      // 修改用户信息并提交
      editUserInfo() {
        // 表单预校验
        this.$refs.myselfRef.validate(async valid => {
          if (!valid) return

          //判断是否修改了图片
          if(this.newsrc!=''){//修改了
            //删除服务器原图
            var formdata2 = new FormData();
            formdata2.append("imgPath", this.myself.img);
            formdata2.append("filename", 'users');
            const {
              data: res
            } = await this.$axios.post(
              'UploadController/removeImg.action', formdata2);
              //赋新值
               this.myself.img=this.newsrc;
          }

          // 发起修改用户信息的数据请求
          // 封装用户信息
          var qs = require('qs')
          const postDatas = qs.stringify({
            userid: this.myself.userid,
            email: this.myself.email,
            username:this.myself.username,
            img:this.myself.img
          })
          const {
            data: res
          } = await this.$axios.post(
            'UserController/updateUser.action', postDatas
          )
          if (res < 1) return this.$message.error('更新用户信息失败！')
          // 关闭对话框
          this.editDialogVisible = false
          // 刷新数据列表
          this.getUserList();
          // 提示修改成功
          this.$message.success('更新用户信息成功！')
        })
      },
      // 阻止upload的自己上传，进行再操作
      async onchange(file, filesList, event) {
        // 创建临时的路径来展示图片
        var windowURL = window.URL || window.webkitURL
        this.src = windowURL.createObjectURL(file.raw)
        //上传图片到后端
        const config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        var formdata = new FormData();
        formdata.append("file", file.raw);
        formdata.append("imgPath", 'images/users');
        const {
          data: res
        } = await this.$axios.post(
          'UploadController/addImg.action', formdata, config
        )
        //console.log(res);
        this.newsrc = res; //赋值数据

      }, // 删除图片
      async handleRemove(file, filesList) {
        //去后端把服务器的指定图片删了
        var formdata2 = new FormData();
        formdata2.append("imgPath", this.newsrc);
        formdata2.append("filename", 'users');
        const {
          data: res
        } = await this.$axios.post(
          'UploadController/removeImg.action', formdata2)
        //  console.log(res);
        //前端删除
        this.src = '';
        this.newsrc='';
      }


    }
  }
</script>


<style>
  .myleft {
    width: 250px;
    height: 285px;
    margin-left: 30px;
    float: left;
  }

  .myright {
    width: 320px;
    height: 285px;
    float: left;
    margin-left: 50px;
  }

  .myleft img {
    width: 100%;
    height: 90%;
    border: 1px solid #000000;
    border-radius:50%;
  }

  .mytitle {
    font-size: 22px;
  }
</style>
